import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import leanCloudAPI from '../api/leancloud.js'

export const useUserStore = defineStore('user', () => {
  // 用户信息
  const userInfo = ref(null)
  
  // 是否已登录
  const isLoggedIn = computed(() => !!userInfo.value)
  
  // 用户对象ID
  const userId = computed(() => userInfo.value?.objectId || null)
  
  // 用户名
  const username = computed(() => userInfo.value?.username || '')
  
  // 从本地存储加载用户信息
  const loadUserFromStorage = () => {
    try {
      const storedUser = localStorage.getItem('userInfo')
      if (storedUser) {
        userInfo.value = JSON.parse(storedUser)
      }
    } catch (error) {
      console.error('加载用户信息失败:', error)
      localStorage.removeItem('userInfo')
    }
  }
  
  // 用户登录
  const login = async (username, password) => {
    try {
      const result = await leanCloudAPI.login(username, password)
      
      if (result.success) {
        userInfo.value = result.data
        localStorage.setItem('userInfo', JSON.stringify(result.data))
        return { success: true }
      } else {
        return { success: false, error: result.error }
      }
    } catch (error) {
      console.error('登录异常:', error)
      return { success: false, error: '登录失败，请稍后重试' }
    }
  }
  
  // 用户注册
  const register = async (userData) => {
    try {
      const result = await leanCloudAPI.register(userData)
      
      if (result.success) {
        userInfo.value = result.data
        localStorage.setItem('userInfo', JSON.stringify(result.data))
        return { success: true }
      } else {
        return { success: false, error: result.error }
      }
    } catch (error) {
      console.error('注册异常:', error)
      return { success: false, error: '注册失败，请稍后重试' }
    }
  }
  
  // 用户登出
  const logout = () => {
    userInfo.value = null
    localStorage.removeItem('userInfo')
  }
  
  // 更新用户信息
  const updateUserInfo = async (updateData) => {
    if (!userInfo.value?.objectId) {
      return { success: false, error: '用户未登录' }
    }
    
    try {
      const result = await leanCloudAPI.updateUserInfo(userInfo.value.objectId, updateData)
      
      if (result.success) {
        // 更新本地用户信息
        userInfo.value = { ...userInfo.value, ...updateData }
        localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
        return { success: true }
      } else {
        return { success: false, error: result.error }
      }
    } catch (error) {
      console.error('更新用户信息失败:', error)
      return { success: false, error: '更新失败，请稍后重试' }
    }
  }
  
  // 刷新用户信息
  const refreshUserInfo = async () => {
    if (!userInfo.value?.objectId) {
      return { success: false, error: '用户未登录' }
    }
    
    try {
      const result = await leanCloudAPI.getUserInfo(userInfo.value.objectId)
      
      if (result.success) {
        userInfo.value = result.data
        localStorage.setItem('userInfo', JSON.stringify(result.data))
        return { success: true }
      } else {
        return { success: false, error: result.error }
      }
    } catch (error) {
      console.error('刷新用户信息失败:', error)
      return { success: false, error: '刷新失败，请稍后重试' }
    }
  }
  
  // 检查字段是否已存在
  const checkFieldExists = async (field, value) => {
    try {
      let checkResult
      switch (field) {
        case 'username':
          checkResult = await leanCloudAPI.checkUsernameExists(value)
          break
        case 'email':
          checkResult = await leanCloudAPI.checkEmailExists(value)
          break
        case 'phone':
          checkResult = await leanCloudAPI.checkPhoneExists(value)
          break
        default:
          return { exists: false }
      }
      
      return checkResult
    } catch (error) {
      console.error(`检查${field}失败:`, error)
      return { exists: false, error: '检查失败' }
    }
  }
  
  // 初始化时加载用户信息
  loadUserFromStorage()
  
  return {
    userInfo,
    isLoggedIn,
    userId,
    username,
    login,
    register,
    logout,
    updateUserInfo,
    refreshUserInfo,
    checkFieldExists
  }
})
